import React, { useState } from 'react'
import { Form, Input, Button, Popup } from 'antd-mobile'
import { login } from '@/models'
import { useNavigate } from 'react-router-dom';
import { saveUserId } from '@/store/userSlice'
import { useDispatch } from 'react-redux';
import { NavBar } from 'antd-mobile'
import { Cell } from 'react-vant'

export default function Login() {
  let [visible, setVisible] = useState(false) //弹出层默认是不可见的
  let [message, setMessage] = useState("") //弹出层的消息
  let navigate = useNavigate();
  let dispatch = useDispatch()

  const back = () => navigate(-1)
  const submit = ({ loginname, password }) => {

    login({ loginname, password }).then((res) => {  //调用登录请求进行登录
      console.log(res)
      if (res.code === "200") {
        localStorage.setItem("token", res.data.token) //记录token
        //向仓库里记录用户id
        dispatch(saveUserId(res.data.userid))
        //显示弹出消息
        setVisible(true)
        setMessage(res.message)
        setTimeout(() => {
          setVisible(false) //关闭弹框
          navigate("/home");  //登录后进入首页
        }, 2000)

      }
    })
  }

  return (
    <div>
      <NavBar back='返回' style={{ marginBottom: '20px', backgroundColor: '#fff', borderBottom: '1px solid #ccc' }} onBack={back}>
        登录
      </NavBar>
      <Popup
        visible={visible}
        mask={false}
        onClose={() => {
          setVisible(false)
        }}
        position='top'
        bodyStyle={{ height: '5vh', 'textAlign': 'center', 'background': "green", 'color': 'white', 'lineHeight': "5vh" }}
      >
        {message}
      </Popup>
      <Form layout='horizontal' onFinish={submit} style={{ display: 'block', padding: '10px', boxSizing: 'border-box' }}>
        <Form.Item label='手机号' name='loginname'>
          <Input placeholder='请输入' />
        </Form.Item>
        <Form.Item label='密码' name='password'>
          <Input type='password' placeholder='请输入' />
        </Form.Item>
        <div style={{ backgroundColor: '#f6f6f6' }}>
          <Button block type='submit' color='primary' shape='rounded' size='large' >提交</Button>
        </div>
      </Form>
      <h3>去注册</h3>
      <Cell title='快速注册' isLink onClick={() => navigate('/regist/step1')} />
    </div >
  )
}
